/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.chengcang.com
 * <p>
 * 版权所有，侵权必究！
 */

package com.chengcang.api.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chengcang.api.modules.login.utils.UserHolder;
import com.chengcang.api.modules.sys.dto.SysUserDTO;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 公共字段，自动填充值
 *
 * @author zhanli
 */
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATE_DATE = "createDate";
    private final static String CREATOR = "creator";
    private final static String UPDATE_DATE = "updateDate";
    private final static String UPDATER = "updater";
    private final static String DEPT_ID = "deptId";
    private final static String DELETED = "deleted";
    private final static String TENANT_ID = "tenantId";

    @Override
    public void insertFill(MetaObject metaObject) {
        SysUserDTO user = UserHolder.getUser();
        Date date = new Date();
        if (user != null) {
            //创建者
            strictInsertFill(metaObject, CREATOR, Long.class, user.getId());
            //创建时间
            strictInsertFill(metaObject, CREATE_DATE, Date.class, date);

            //创建者所属部门
            strictInsertFill(metaObject, DEPT_ID, Long.class, user.getDeptId());

            //更新者
            strictInsertFill(metaObject, UPDATER, Long.class, user.getId());
            //更新时间
            strictInsertFill(metaObject, UPDATE_DATE, Date.class, date);
            // 逻辑删除
            strictInsertFill(metaObject, DELETED, Integer.class, 0);
            // 租户ID
            strictInsertFill(metaObject, TENANT_ID, Long.class, user.getDefaultTenantId());
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        SysUserDTO user = UserHolder.getUser();
        if (user != null) {
            //更新者
            strictUpdateFill(metaObject, UPDATER, Long.class, UserHolder.getUser().getId());
            //更新时间
            strictUpdateFill(metaObject, UPDATE_DATE, Date.class, new Date());
        }
    }
}